package com.scalar.chiptrack.sales.actions;


import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.operations.orderscheduling.dao.OrderSchedulingDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.SalesOrderHelper;
import com.scalar.chiptrack.sales.dao.*;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;


public final class ApproveOrderAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/approveOrder.do";

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        ApproverOrderForm subform = ( ApproverOrderForm ) form;
        String action = request.getParameter ( "action" );
        String byDate = request.getParameter ( "byDate" );

        HttpSession session = request.getSession ();
        User user           = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        int isSample        = 1; //default set to salesOrder
        if ( ( request.getParameter ( "isSample" ) != null ) && ( !request.getParameter ( "isSample" ).equals ( "null" ) ) )
        {
            isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
        }
        
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString ()+ "&requestOrderSchedulingSearch="+request.getParameter ("requestOrderSchedulingSearch") +"&isSample="+request.getParameter("isSample") );
            return ( mapping.findForward ( "login" ) );
        }

        HashMap errors = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

        HashMap info = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );

        if ( ( action != null ) && ( action.equals ( "ApproveOrder" ) ) )
        {

            int salesOrderId            = subform.getSalesOrderId ();
            DBTransaction dbTransaction = null;
            boolean success             = false;
            boolean isApproved          = false;
            String changeSummary        = "";
            String actions              = "";

            try
            {
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                String[] lineItemIds        = request.getParameterValues ( "lineItemId" );
                String[] scheduleDates      = request.getParameterValues ( "scheduleDate" );
                String[] marketingHolds     = request.getParameterValues ( "marketingHold" );
                String[] financeHolds       = request.getParameterValues ( "financeHold" );
                String[] operationsHolds    = request.getParameterValues ( "operationsHold" );
                String[] salesHolds         = request.getParameterValues ( "salesHold" );
                String[] requestDates       = request.getParameterValues ("requestDate");
                ArrayList cancelledLineitems = new ArrayList ();
                String actions1             = new String ();
                double[] subTotalAndTax     = new double[5];
				double[] subTotalAndTax1    = new double[5];

                //Load all the actions taken in this period
                actions = SalesDAO.loadActionsPeformed ( dbTransaction, lineItemIds, marketingHolds, financeHolds, operationsHolds, salesHolds, salesOrderId, scheduleDates );

                //For gettig the summary of changes done to the holds of line itemds
                changeSummary = SalesDAO.loadActionsPeformedSummary ( dbTransaction, lineItemIds, marketingHolds, financeHolds, operationsHolds, salesHolds, scheduleDates, salesOrderId );

                subTotalAndTax = SalesDAO.loadActionValue ( dbTransaction, salesOrderId );

                //Approve the salesOrderId
                SalesDAO.approveSalesOrder ( dbTransaction, salesOrderId, lineItemIds, requestDates, scheduleDates, marketingHolds, financeHolds, operationsHolds, salesHolds, user );

                cancelledLineitems = SalesDAO.loadCancelValue ( dbTransaction, lineItemIds );
                int numberOflineitems = cancelledLineitems.size ();
                String[] lineitems = new String[numberOflineitems];
                boolean flag = false;
                if ( cancelledLineitems != null )
                {
                    for ( int i = 0; i < numberOflineitems; i++ )
                    {
                        flag = true;
                        lineitems[i] = ( String ) cancelledLineitems.get ( i );
                    }
                }

                if ( flag == true )
                {
                    if ( numberOflineitems > 1 )
                    {
                        actions = actions + "<br> Hence the above " + numberOflineitems + " Lineitems are Cancelled";
                    }
                    else
                    {
                        actions = actions + "<br> Hence the above  Lineitem is Cancelled";
                    }
                    subTotalAndTax1 = SalesDAO.loadActionValue ( dbTransaction, salesOrderId );

                    if ( subTotalAndTax[0] != subTotalAndTax1[0] )
                    {
                        actions1 = actions1 + "SubTotal is Changed from <b><I>" + StringUtils.formatAmountWithNoOfDecimals(subTotalAndTax[0])+ "</I></b> to <b><I>" + StringUtils.formatAmountWithNoOfDecimals(subTotalAndTax1[0]) + "</I></b>";
                    }
                    if ( subTotalAndTax[1] != subTotalAndTax1[1] )
                    {
                        actions1 = actions1 + "<br>Sales Tax is Changed from <b><I>" +StringUtils.formatAmountWithNoOfDecimals(subTotalAndTax[1])  + "</I></b>  to  <b><I> " + StringUtils.formatAmountWithNoOfDecimals(subTotalAndTax1[1]) + "</I></b>";
                    }
                }
                //To save correct actions and comments
                if ( actions1 != null && actions != null )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), actions, subform.getApproverComments () );
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), actions1, "" );
                }
                else if ( actions != null )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), actions, subform.getApproverComments () );
                }
                else if ( actions1 != null )
                {
                    SalesDAO.updateSalesAuditTrail ( dbTransaction, salesOrderId, user.getUserId (), actions1, subform.getApproverComments () );
                }

                success = true;

                String status = SalesDAO.loadOrderStatus ( dbTransaction, salesOrderId );

                if ( status.trim ().length () == 0 )
                {
                    status = " Approved Successfully";
                    isApproved = true;
                }
                else
                {
                    status = "Still Under " + status;
                }

                request.setAttribute ( "status", status );
                request.setAttribute ( "salesOrderId", Integer.toString ( salesOrderId ) );
            }
            catch ( ScalarException se )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_APPROVING_SALES_ORDER );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Approve sales order ID: " + salesOrderId );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                if ( success == true )
                {
                    dbTransaction.commit ();

                    info.put ( "SalesOrder = " + subform.getSalesOrderNo (), ( String ) request.getAttribute ( "status" ) );
                    info.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder(" + salesOrderId + ");'onmouseover=\"window.status='Click here to View/print Sales Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );

                    try
                    {
                        SalesDAO.updateAlarmAndSendMailWithChangeSummary ( subform.getApproverComments(), salesOrderId, isApproved, user, changeSummary );
                        //notifyApprovedSalesOrderInfo ( salesOrderId );
                        SalesOrderHelper.notifyApprovedSalesOrderInfo ( salesOrderId );
                        info.put ( "Email ", " has been sent to all approvers" );
                        //notifyFinanceReasonCode ( salesOrderId );
                    }
                    catch ( Exception ex )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Send Mail to all Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, ex );
                    }

                }
                else
                {
                    dbTransaction.rollback ();

                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_APPROVING_SALES_ORDER );
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Approve sales order ID: " + salesOrderId );
                    session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                }
            }

            // Checks whether the request is from Order Scheduling Search Screen. If yes, forwards back to the Order Scheduling Search Screen
            if ( ( request.getParameter ( "requestOrderSchedulingSearch" ) != null ) && ( request.getParameter ( "requestOrderSchedulingSearch" ).equals ( "true" ) ) )
            {
                return ( mapping.findForward ( "successOrderSchedulingSearchRequest" ) );
            }

            return ( mapping.findForward ( "successPending" ) );
        }
        else if ( ( action != null ) && ( action.equals ( "RejectOrder" ) ) )
        {

            int salesOrderId = subform.getSalesOrderId ();

            try
            {
                SalesDAO.updateHoldTable ( null, salesOrderId, false, user );

                errors.put ( "SalesOrder = " + subform.getSalesOrderNo (), "Rejected Successfully" );
                errors.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Sales Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );

                try
                {
                    SalesDAO.updateAlarm ( subform.getApproverComments (), salesOrderId, false, user );
                    SalesOrderDAO.sendMailToCustomer ( salesOrderId ); // If the order is approved then it needs to send to customer
                    errors.put ( "Email ", " has been sent to all approvers" );
                }
                catch ( Exception exc )
                {
                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Send Mail to all Approvers" );
                    session.setAttribute ( SessionKeys.ERROR_REPORT, exc );
                }


            }
            catch ( Exception ex )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_REJECTING_SALES_ORDER );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Reject Sales Order ID: " + salesOrderId );
                session.setAttribute ( SessionKeys.ERROR_REPORT, ex );
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
            }
            return ( mapping.findForward ( "success" ) );
        }
        else if ( ( action != null ) && ( action.equals ( "ApproveMissedOrder" ) ) )
        {
            String salesOrderId = request.getParameter ( "salesOrderId" );
            String changesSummary = "";
            boolean success = false;
            try
            {
                String[] lineItemIds = request.getParameterValues ( "lineItemId" );
                String[] revisedDates = request.getParameterValues ( "revisedDate" );
                request.setAttribute ( "salesOrderId", salesOrderId );
                subform.setRevisedDate ( revisedDates );
                changesSummary = SalesDAO.loadRevisedDateChangesSummary ( null, lineItemIds, revisedDates );
                SalesDAO.approveMissedOrder ( lineItemIds, revisedDates, user );
                if ( changesSummary != null && changesSummary.trim().length() > 0 )
                {
                    SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt(salesOrderId), user.getUserId (), changesSummary, "" );
                }
                String lineItemsIds = StringUtils.concatStrings(lineItemIds,",");
                ArrayList reAllocatedLineItems = OrderSchedulingDAO.reAllocateAllBackLog( null, lineItemsIds );
                int lineItemsSize = (reAllocatedLineItems == null) ? 0 : reAllocatedLineItems.size();
                String lineItemNos = "";
                for ( int i=0;  i < lineItemsSize; i++ )
                {
                    LineItem lineItem = (LineItem)reAllocatedLineItems.get(i);
                    if ( ! "SUCCESS".equalsIgnoreCase( lineItem.getReason() ) ) //COULD NOT RESERVE LOTS FOR THIS LINE ITEM
                    {
                        lineItemNos = lineItemNos + ", " + lineItem.getLineItemNo();
                    }
                }
                lineItemNos = lineItemNos.replaceFirst( ",", "" );
                if ( lineItemNos.length() > 0 )
                {
                    errors.put( "Could not Reserve the Inventory for the line Item no(s)", lineItemNos );
                }

                success = true;
            }
            catch ( Exception ex )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_RESCHEDULING_SALES_ORDER );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, "Error: Could not Reschedule sales order ID: " + salesOrderId );
                session.setAttribute ( SessionKeys.ERROR_REPORT, ex );
            }
            finally
            {
                if ( success )
                {
                    info.put ( "SalesOrder = " + subform.getSalesOrderNo (), "rescheduled Successfully" );
                    //info.put ( "Email ", " has been sent to all approvers" );
                    info.put ( "View/Print ", "Click here to <a href='javascript:openSalesOrder();' onmouseover=\"window.status='Click here to View/print Sales Order';return true\" onmouseout=\"window.status='';return true\" > view/print </a>Sales Order Details" );
                    try
                    {
                        SalesDAO.updateAlarmAndSendMailWithChangeSummary ( subform.getApproverComments (), Integer.parseInt ( salesOrderId ), true, user, changesSummary );
                        SalesOrderHelper.notifyApprovedSalesOrderInfo ( Integer.parseInt ( salesOrderId ) );
                        info.put ( "Email ", " has been sent to all approvers" );
                    }
                    catch( Exception e  )
                    {
                        info.put ( "Email ", ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        info.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could not Send mails to Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                    }
                }
            }


            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
            }
            if ( !info.isEmpty () )
            {
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }

            if ( ( session.getAttribute ( "ViewOrderRequest" ) != null ) && ( "true".equalsIgnoreCase((String)session.getAttribute ( "ViewOrderRequest" )) ) )
            {
                session.removeAttribute ( "SalesOrderHoldReleaseRequest" );
                return ( mapping.findForward ( "successViewOrdersList" ) );
            }
            else if ( ( session.getAttribute ( "SalesOrderHoldReleaseRequest" ) != null ) && ( "true".equalsIgnoreCase((String)session.getAttribute ( "SalesOrderHoldReleaseRequest" )) ) )
            {
                session.removeAttribute ( "ViewOrderRequest" );
                return ( mapping.findForward ( "successSalesHoldReleaseList" ) );
            }
            else
            {
                session.removeAttribute ( "ViewOrderRequest" );
                session.removeAttribute ( "SalesOrderHoldReleaseRequest" );
                return ( mapping.findForward ( "successMissedOrdersList" ) );
            }
        }
        else if ( ( action != null ) && ( action.equals ( "splitLineItems" ) ) )
        {
            request.setAttribute("frmPending","1");
            return new ActionForward("/splitSalesOrder.do?frmPending=1&salesOrderId="+subform.getSalesOrderId(), false);
        }
        else if ( request.getParameter ( "salesOrderId" ) != null )
        {
            String salesOrderId = request.getParameter ( "salesOrderId" );

            // This checks whether any of the line items in a sales order is still in hold. If not,  forwards to the view page.
            if ( ( request.getParameter ( "requestOrderSchedulingSearch" ) != null ) && ( request.getParameter ( "requestOrderSchedulingSearch" ).equalsIgnoreCase ( "true" ) ) )
            {
                String status = SalesOrderDAO.getLineItemStatusBySalesOrderId ( salesOrderId );
                request.setAttribute ( "requestOrderSchedulingSearch", "true" );
                if ( status.indexOf ( "HOLD BY" ) == -1 )
                {
                    if ( salesOrderId != null && !"".equals(salesOrderId) )
                    {
                        request.setAttribute ( "isSample", SalesOrderDAO.getOrderType ( null, Integer.parseInt( salesOrderId ) ) );
                    }
                    return mapping.findForward ( "salesOrderViewMain" );
                }
            }
            SalesOrder salesOrder = null;
            try
            {
                salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId );
                request.setAttribute ( "isSample", ( salesOrder.getIsSample () ? "0" : "1" ) );
            }
            catch( Exception e )
            {
                errors.put( ERROR_SALES_ORDER_INFORMATION_MISSING, null );
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                if ( ( action != null ) && ( action.equals ( "missedOrder" ) ) )
                {
                    return  mapping.findForward( "missedOrdersSearch" );
                }
                else
                {
                    return  mapping.findForward( "pendingOrdersSearch" );
                }
            }

            if ( isSample == 1  && user.isActionAllowed ( Functionality.SALES_PENDING_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else if ( isSample == 0  && user.isActionAllowed ( Functionality.SAMPLE_PENDING_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            HashMap holds = SalesDAO.loadHoldsForOrder ( salesOrder.getSalesOrderId () );
            Iterator holdBy = holds.keySet ().iterator ();
            Iterator userBy = holds.values ().iterator ();

            //Loop thru the hold list and set the holds in the form
            while ( holdBy.hasNext () )
            {
                String holdedBy = ( String ) holdBy.next ();
                if ( holdedBy.equalsIgnoreCase ( "Finance" ) )
                {
                    subform.setFinanceHold ( true );
                    subform.setFinanceHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Operations" ) )
                {
                    subform.setOperationsHold ( true );
                    subform.setOperationsHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Sales" ) )
                {
                    subform.setSalesHold ( true );
                    subform.setSalesHoldUser ( ( String ) userBy.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Marketing" ) )
                {
                    subform.setMarketingHold ( true );
                    subform.setMarketingHoldUser ( ( String ) userBy.next () );
                }

            }

            if ( user.isActionAllowed ( Functionality.OP_APPROVAL_RIGHTS, User.USER_ACTION_MODIFY ) == true )
            {
                request.setAttribute ( "isOperations", "TRUE" );
            }
            else
            {
                request.setAttribute ( "isOperations", "FALSE" );
            }


            ArrayList previousLineItems = SalesOrderDAO.loadChangeOrderLineItems ( salesOrder.getSalesOrderId () );
            /*if (  ! (salesOrder.getEndUser ().trim ().equals ( "" ) ) )
            {
                int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, previousLineItems, endUserId );
            }
            else
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems( null, previousLineItems, salesOrder.getCustomerId(), salesOrder.getOdmId() );
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems( null, previousLineItems, salesOrder.getCustomerId(), salesOrder.getOdmId() );
            }*/
            if ( previousLineItems.size () == 0 )
                request.setAttribute ( "showPreviousList", "FALSE" );
            else
                request.setAttribute ( "showPreviousList", "TRUE" );

            //Set the ChangeOrder lineItems
            request.setAttribute ( "previousLineItems", previousLineItems );

            int customerId = SalesOrderDAO.loadCustomerId ( salesOrder.getSalesOrderId () );

            ArrayList list = SalesOrderDAO.loadPendingOrderLineItems ( salesOrder.getSalesOrderId (), customerId );

            if( (request.getParameter("frmMail") != null ) && ( list.size() == 0 ) )
            {
                return mapping.findForward("viewOrder");
            }
            /*if ( !( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
            {
                int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, list, endUserId );
            }
            else
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems( null, list, salesOrder.getCustomerId(), salesOrder.getOdmId() );
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems( null, list, salesOrder.getCustomerId(), salesOrder.getOdmId() );
            }*/
            int totalQty = 0;

		   	double totalAmt = 0.0;
		    double salesTax = 0.0;

            for ( int i = 0; i < list.size (); i++ )
            {
                LineItem item = ( LineItem ) list.get ( i );
                totalQty = totalQty + item.getQuantity ();
                totalAmt = totalAmt + item.getAmountAsDouble ();
                float taxvalue = SalesOrderDAO.getTaxValue ( null, salesOrder.getSalesTaxType () );
                if ( item.getIsTaxable () )
                {
					Float ff = new Float(taxvalue);
					double tax = ff.doubleValue();
					salesTax = salesTax + ( item.getAmountAsDouble () * ( tax / 100 ) );
                }
            }
            //Set the current order lineItems
            request.setAttribute ( "presentLineItems", list );

            request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( list ) );

            subform.setTotalQty ( totalQty );

			salesOrder.setSalesTaxAsDouble(salesTax );
			salesOrder.setSubTotalAsDouble(totalAmt);
			salesOrder.setOrderTotalAsDouble(salesOrder.getSubTotalAsDouble()+salesOrder.getFrieghtAsDouble()+salesOrder.getMiscAsDouble()+salesOrder.getSalesTaxAsDouble());

            subform.setSalesOrder ( salesOrder );
            subform.setSalesOrderId ( salesOrder.getSalesOrderId () );
            subform.setSalesOrderNo ( salesOrder.getSalesOrderNo () );

            request.setAttribute ( "isSample", ( salesOrder.getIsSample () ? "0" : "1" ) );

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "approverOrderForm", subform );

            request.setAttribute ( SessionKeys.INFO_MESSAGES, SalesDAO.loadLineItemHolds ( salesOrder.getSalesOrderId () ) );
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, SalesDAO.loadHoldCancelledLineItems ( salesOrder.getSalesOrderId () ) );
            if ( ( action != null ) && ( action.equals ( "missedOrder" ) ) )
            {
                if ( isSample == 1  && user.isActionAllowed ( Functionality.SALES_MISSED_ORDER, User.USER_ACTION_MODIFY ) )
                {
                    request.setAttribute ( "showMessage", "FALSE" );
                }
                else if ( isSample == 0  && user.isActionAllowed ( Functionality.SAMPLE_MISSED_ORDER, User.USER_ACTION_MODIFY ) )
                {
                    request.setAttribute ( "showMessage", "FALSE" );
                }
                else
                {
                    request.setAttribute ( "showMessage", "TRUE" );
                }
                //To enter Revised Date  for  Approved lineitems
                ArrayList list1 = SalesOrderDAO.loadAllLineItemsExceptShipped ( null, salesOrder.getSalesOrderId (), byDate );

                /*if ( !( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
                {
                    int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, list1, endUserId );
                }
                else
                {
                    SalesOrderDAO.loadCustomerPartNumbersForLineItems( null, list1, salesOrder.getCustomerId(), salesOrder.getOdmId() );
                    NewSalesOrderDAO.loadOdmLabelNumbersForLineItems( null, list1, salesOrder.getCustomerId(), salesOrder.getOdmId() );
                }*/
                request.setAttribute ( "presentLineItems", list1 );
                request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( list1 ) );
                return ( mapping.findForward ( "missedOrder" ) );
            }
            else
            {
                return ( mapping.findForward ( "salesOrder" ) ); //return to the approver page, where approver can approve/reject
            }


        }
        if( "true".equals(request.getParameter("requestOrderSchedulingSearch") ) )
        {
            return ( mapping.findForward ( "successOrderSchedulingSearchRequest" ) );
        }
        else
        {
            return ( mapping.findForward ( "pendingOrdersSearch" ) );
        }
    }

    /*private void notifyApprovedSalesOrderInfo ( int salesOrderId )
    {
        SalesOrder salesOrder = null;
        ArrayList lineItems = null;

        String from     = null;
        String to       = null;
        String cc       = null;
        String subject  = null;
        String message  = null;
        String customerNotificatonEmail = null;


        String shippingMethodLabel  = null;
        String endUserLabel         = null;
        String representativeLabel  = null;
        String endCustomerLabel     = null;
        String heading              = null;
        String deliveryTermsLabel   = null;

        try
        {

            salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId + "" );
            // Enter only if the sales order is approved
            if ( SalesOrderDAO.isSalesOrderApproved ( salesOrder.getSalesOrderId () ) == true )
            {
                //from = "Chiptrac Admin <" + ConfigManager.getSysAdminEmail() + ">";
                from =  ConfigManager.getFromEmailId( Constants.FROM_EMAIL_SALES_GROUP_NAME );
                to = salesOrder.getEnteredByName() + "<" + UserDAO.getEmailByUserId( salesOrder.getEnteredById() ) + ">" ;
                cc = StringUtils.concatStrings( SalesOrderDAO.loadEmailListForApprovedSalesOrderNotification(), Mailer.EMAIL_SEPARATOR ) ;

                if ( ConfigManager.isSendApprovedSalesOrderNotificationMailToCustomer() )
                {
                    customerNotificatonEmail = StringUtils.concatStrings ( NewSalesOrderDAO.loadCustomerNotificationsEmails( salesOrder.getCustomerId() ), Mailer.EMAIL_SEPARATOR );
                    if( customerNotificatonEmail != null && customerNotificatonEmail.trim().length() > 0 )
                    {
                        if( cc == null || cc.trim().length() == 0 )
                        {
                            cc = customerNotificatonEmail;
                        }
                        else
                        {
                            cc = cc + "," + customerNotificatonEmail;
                        }
                    }
                }    

                //Send Notification mail to Customer Contact Person also
                *//*if( salesOrder.getEmail() != null && salesOrder.getEmail().trim().length() > 0 )
                {
                    if( cc == null || cc.trim().length() == 0 )
                    {
                        cc = salesOrder.getEmail();
                    }
                    else
                    {
                        cc = cc + "," + salesOrder.getEmail();
                    }
                }*//*

                
                String method = salesOrder.getShippingMethodName();
				String shippingMethod  = null ;

                if(method != null && method.trim().length()!= 0)
				{
					 shippingMethod = salesOrder.getShippingMethodName() +"#"+ salesOrder.getShippingAccount();
				}
				else
				{
					shippingMethod = "";
				}

                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                try
                {
                    endCustomerLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                    if ( endCustomerLabel == null )
                    {
                        endCustomerLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endCustomerLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                }
                try
                {
                    endUserLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endUser" );
                    if ( endUserLabel == null )
                    {
                        endUserLabel = Labels.DEFAULT_END_USER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endUserLabel    = Labels.DEFAULT_END_USER_LABEL;
                }

                try
                {
                    representativeLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesRep.Name" );
                    if ( representativeLabel == null )
                    {
                        representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                    }
                }
                catch ( NullPointerException e )
                {
                    representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                }

                try
                {
                    deliveryTermsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.DeliveryTerms" );
                    if ( deliveryTermsLabel == null )
                    {
                        deliveryTermsLabel = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    deliveryTermsLabel    = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                }

                if ( salesOrder.getIsSample() )
                {
                    subject = "Sample Order " + salesOrder.getSalesOrderNo() + " has been approved";
                    heading = "sample";
                }
                else
                {
                    subject = "Sales Order " + salesOrder.getSalesOrderNo() + " has been approved";
                    heading = "sales";
                }
                message = "<HTML><BODY><P style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana'>This is to notify that the "+heading+" order <b>" + salesOrder.getSalesOrderNo() + "</b> has been approved. <BR><BR><TABLE WIDTH=677 BORDER=0 CELLPADDING=4 CELLSPACING=0 style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana'><TR BGCOLOR=\"#ccccff\"><TH COLSPAN=5 WIDTH=669 HEIGHT=20 VALIGN=CENTER><P ALIGN=LEFT>"+heading.replaceFirst("s","S")+" Order Information:</P></TH></TR>" +
                            "<TR BGCOLOR=\"#e6e6e6\"><TD WIDTH=136 VALIGN=TOP><P style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana'>Sale Order No:</P></TD><TD WIDTH=167 VALIGN=BOTTOM SDVAL=\"10185\" SDNUM=\"1033;\"><P ALIGN=LEFT>" +
                            salesOrder.getSalesOrderNo() + "</P></TD><TD WIDTH=33 VALIGN=TOP><P><BR></P></TD><TD WIDTH=134 VALIGN=TOP><P>Customer Name:</P></TD><TD WIDTH=167 VALIGN=TOP><P>" +
                            salesOrder.getCustomerName() + "</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Customer PO:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getCustomerPO() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Contact Person:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getContactPerson() +	"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Phone No:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getPhoneNumber() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Cell No:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getCellNumber() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Fax :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getFaxNumber() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Email:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getEmail() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Sales Person:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getSalesPerson() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+representativeLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getSalesRep() +	"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>"+shippingMethodLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            shippingMethod+"</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT></P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
							"" +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Pay Terms :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getShippingTerms() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+deliveryTermsLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getDeliveryTerms() +	"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Regional Rep :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getRegionalRep() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Booking Date:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getSalesOrderDate() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>"+endUserLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getEndCustomer() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+endCustomerLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getOdm() + "</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Billing Address :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getBillingAddress() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Shipping Address:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getShippingAddress() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Freigh Instructions :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getFreightInstructions() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Shipping Instructions :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getShippingInstructions() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Comments :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                            salesOrder.getComments() + 	"</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT></P></TD><TD WIDTH=167><P ALIGN=LEFT></TD></TR></TABLE></BODY></HTML>";

                Mailer.send( from,
                             to,
                             cc,
                             null *//*bcc*//*,
                             subject,
                             message,
                             null *//*attachments*//*,
                             Mailer.CONTENT_TYPE_HTML,
                             false *//*Dont verify if the receipient is a ChipTrac user*//* );
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            System.out.println ( "WARNING!! Could not notify " + to + " about the approved sales order: " + salesOrder.getSalesOrderNo () );
        }
    }*/

    private void notifyFinanceReasonCode ( int salesOrderId )
    {
        SalesOrder salesOrder = null;

        String from = null;
        String to = null;
        String cc = null;
        String subject = null;
        String message = null;

        try
        {
            salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId + "" );
            if ( SalesOrderDAO.isSalesOrderApprovedButFinanceReasonCode ( salesOrder.getSalesOrderId () ) == true )
            {
                //from = "Chiptrac Admin <" + ConfigManager.getSysAdminEmail () + ">";
                from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME );
                to = salesOrder.getEnteredByName () + "<" + UserDAO.loadEmailByInternalUserId( null, salesOrder.getEnteredById () ) + ">";
                cc = StringUtils.concatStrings ( SalesOrderDAO.loadEmailListForApprovedSalesOrderNotification (), Mailer.EMAIL_SEPARATOR );

                //Send Notification mail to Customer Contact Person also
                /*if( salesOrder.getEmail() != null && salesOrder.getEmail().trim().length() > 0 )
                {
                    if( cc == null || cc.trim().length() == 0 )
                    {
                        cc = salesOrder.getEmail();
                    }
                    else
                    {
                        cc = cc + "," + salesOrder.getEmail();
                    }
                }*/
                String method = salesOrder.getShippingMethodName();
				String shippingMethod  = null ;
				if( method != null && method.trim().length()!= 0 )
				{
					 shippingMethod = salesOrder.getShippingMethodName() + "#" + salesOrder.getShippingAccount();
				}
				else
				{
					shippingMethod = "";
				}
                String shippingMethodLabel = null;
                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                String endCustomerLabel = null;
                try
                {
                    endCustomerLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                    if ( endCustomerLabel == null )
                    {
                        endCustomerLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endCustomerLabel    = Labels.DEFAULT_END_CUSTOMER_LABEL;
                }
                String endUserLabel = null;
                try
                {
                    endUserLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endUser" );
                    if ( endUserLabel == null )
                    {
                        endUserLabel = Labels.DEFAULT_END_USER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endUserLabel    = Labels.DEFAULT_END_USER_LABEL;
                }
                String representativeLabel = null;
                try
                {
                    representativeLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesRep.Name" );
                    if ( representativeLabel == null )
                    {
                        representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                    }
                }
                catch ( NullPointerException e )
                {
                    representativeLabel = Labels.DEFAULT_REPRESENTATIVE;
                }
                String deliveryTermsLabel = null;
                try
                {
                    deliveryTermsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.DeliveryTerms" );
                    if ( deliveryTermsLabel == null )
                    {
                        deliveryTermsLabel = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    deliveryTermsLabel    = Labels.DEFAULT_DELIVERY_TERMS_LABEL;
                }
                String heading = null;
                if ( salesOrder.getIsSample() )
                {
                    subject = "All the holds except finance have been removed on the Sample Order " + salesOrder.getSalesOrderNo () + "";
                    heading = "sample";
                }
                else
                {
                    subject = "All the holds except finance have been removed on the Sales Order " + salesOrder.getSalesOrderNo () + "";
                    heading = "sales";
                }

                message = "<HTML><BODY><P style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana'>This is to notify that all the holds except for the finance have been removed on the "+heading+" order <b>" + salesOrder.getSalesOrderNo () + "</b> . <BR><BR><TABLE WIDTH=677 BORDER=0 CELLPADDING=4 CELLSPACING=0 style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana'><TR BGCOLOR=\"#ccccff\"><TH COLSPAN=5 WIDTH=669 HEIGHT=20 VALIGN=CENTER><P ALIGN=LEFT>"+heading.replaceFirst("s","S")+" Order Information:</P></TH></TR>" +
                        "<TR BGCOLOR=\"#e6e6e6\"><TD WIDTH=136 VALIGN=TOP><P>Sale Order No:</P></TD><TD WIDTH=167 VALIGN=BOTTOM SDVAL=\"10185\" SDNUM=\"1033;\"><P ALIGN=LEFT>" +
                        salesOrder.getSalesOrderNo () + "</P></TD><TD WIDTH=33 VALIGN=TOP><P><BR></P></TD><TD WIDTH=134 VALIGN=TOP><P>Customer Name:</P></TD><TD WIDTH=167 VALIGN=TOP><P>" +
                        salesOrder.getCustomerName () + "</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Customer PO:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getCustomerPO () + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Contact Person:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getContactPerson () + "</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Phone No:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getPhoneNumber() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Cell No:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getCellNumber() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Fax :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getFaxNumber() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Email:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getEmail() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Sales Person:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getSalesPerson() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+representativeLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getSalesRep() +	"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>"+shippingMethodLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        shippingMethod+"</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT></P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        "" +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Pay Terms :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getShippingTerms() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+deliveryTermsLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getDeliveryTerms() +	"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Regional Rep :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getRegionalRep() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Booking Date:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getSalesOrderDate() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>"+endUserLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getEndCustomer() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>"+endCustomerLabel+" :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getOdm() + "</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Billing Address :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getBillingAddress() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Shipping Address:</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getShippingAddress() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Freigh Instructions :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getFreightInstructions() + "</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT>Shipping Instructions :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getShippingInstructions() +"</P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT>Comments :</P></TD><TD WIDTH=167><P ALIGN=LEFT>" +
                        salesOrder.getComments() + 	"</P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT></P></TD><TD WIDTH=167><P ALIGN=LEFT></TD></TR></TABLE></BODY></HTML>";


                Mailer.send ( from,
                              to,
                              cc,
                              null /*bcc*/,
                              subject,
                              message,
                              null /*attachments*/,
                              Mailer.CONTENT_TYPE_HTML,
                              false /*Dont verify if the receipient is a ChipTrac user*/ );

            }
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            System.out.println ( "WARNING!! Could not notify " + to + " about the finance reason code for the  sales order: " + salesOrder.getSalesOrderNo () );
        }
    }
}
